#!/usr/bin/env bash

if [ -z "${KB_GTM_LEADER}" ]; then
  log:info "Starting postgres as master gtm"
  sed -i "s|startup = STANDBY|#startup = ACT|" "${PGDATA}/gtm.conf"
  sed -i "s|active_host = '*|#active_host = ''|" "${PGDATA}/gtm.conf"
  sed -i "s|active_port = 6666|#active_port =|" "${PGDATA}/gtm.conf"
else
  log:info "Starting postgres as standby gtm"
  if [ "${KB_GTM_LEADER}" == "" ]; then
    log:warning "No primary found, waiting for first datanode."
    KB_GTM_LEADER="${KB_CLUSTER_COMP_NAME}-0"
  fi
  MASTER_SERVICE="${KB_GTM_LEADER}.${KB_CLUSTER_COMP_NAME}-headless"
  sed -i "s|#startup = ACT|startup = STANDBY|" "${PGDATA}/gtm.conf"
  sed -i "s|#active_host = ''|active_host = '${MASTER_SERVICE}'|" "${PGDATA}/gtm.conf"
  sed -i "s|#active_port =|active_port = 6666|" "${PGDATA}/gtm.conf"
fi
